
import axios from 'axios'
import {
  Modal,
  notification
} from 'ant-design-vue'

// axios.defaults.withCredentials = true
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
// axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded'
// axios.defaults.transformRequest = [function (data) {
//   let ret = ''
//   for (let it in data) {
//     ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
//   }
//   return ret
// }]

/**
 * 【指定 axios的 baseURL】
 * 则映射后端域名，通过 vue.config.js
 * @type {*|string}
 */
const ACCESS_TOKEN = 'Token'
const ryAxios = {
  install (Vue, store, process) {
    let apiBaseUrl = process.env.BASE_URL
    let APPID = process.env.APPID
    // 创建 axios 实例
    const service =
      axios.create({
        baseURL: apiBaseUrl, // api base_url
        timeout: 600000 // 请求超时时间
      })
    const err = error => {
      if (error.response) {
        let data = error.response.data
        const token = Vue.ls.get(ACCESS_TOKEN)
        // console.log("------异常响应------", token)
        // console.log("------异常响应------", error.response.status)
        switch (error.response.status) {
          case 403:
            notification.error({
              message: '系统提示',
              description: error.response.statusText,
              duration: 4
            })
            break
          case 500:
            if (token && data.message === 'Token失效，请重新登录') {
              Modal.error({
                title: '登录已过期',
                content: '很抱歉，登录已过期，请重新登录',
                okText: '重新登录',
                mask: false,
                onOk: () => {
                  store.dispatch('Logout').then(() => {
                    Vue.ls.remove(ACCESS_TOKEN)
                    window.location.reload()
                  })
                }
              })
            }
            break
          case 404:
            notification.error({
              message: '系统提示',
              description: '很抱歉，资源未找到!',
              duration: 4
            })
            break
          case 504:
            notification.error({
              message: '系统提示',
              description: '网络超时'
            })
            break
          case 401:
            notification.error({
              message: '系统提示',
              description: '未授权，请重新登录',
              duration: 4
            })
            if (token) {
              store.dispatch('Logout').then(() => {
                setTimeout(() => {
                  window.location.reload()
                }, 1500)
              })
            }
            break
          default:
            notification.error({
              message: '系统提示',
              description: data.message,
              duration: 4
            })
            break
        }
      }
      return Promise.reject(error)
    }

    // request interceptor
    service.interceptors.request.use(
      config => {
        config.headers['APPID'] = APPID
        const token = Vue.ls.get(ACCESS_TOKEN)
        if (token) {
          config.headers['Access-Token'] = `${token}`
          // config.headers[ 'Cookie' ] = `Admin-token=${token}` // 让每个请求携带自定义 token 请根据实际情况自行修改
        }
        // if(config.method == 'get'){
        //     config.params = {
        //       _t: Date.parse(new Date())/1000,
        //       ...config.params
        //     }
        // }
        return config
      },
      error => {
        return Promise.reject(error)
      }
    )

    // response interceptor
    service.interceptors.response.use(response => {
      let data = response.data || response
      console.log('request', data)
      if (data instanceof Blob) {
        return response
      }
      const token = Vue.ls.get(ACCESS_TOKEN)
      const warnStatus = response.headers['warn-status'] // 默认提醒错误信息
      if (
        !window.isSuccess(data)
      ) {
        switch (data.errorCode) {
          case 403:
            !warnStatus &&
              notification.error({
                message: '错误提示',
                description: '拒绝访问',
                duration: 4
              })
            break
          case 404:
            !warnStatus &&
              notification.error({
                message: '错误提示',
                description: '很抱歉，资源未找到!',
                duration: 4
              })
            break
          case 504:
            !warnStatus &&
              notification.error({
                message: '错误提示',
                description: '网络超时'
              })
            break
          case 401:
            !warnStatus &&
              notification.error({
                message: '错误提示',
                description: '未授权，请重新登录',
                duration: 4
              })
            if (token) {
              store.dispatch('Logout').then(() => {
                setTimeout(() => {
                  Vue.ls.remove(ACCESS_TOKEN)
                  window.location.reload()
                }, 1500)
              })
            }
            break
          default:
            !warnStatus &&
              notification.error({
                message: '系统提示',
                description: data.message || '未知错误',
                duration: 4
              })
            break
        }
      }
      return response.data
    }, err)
    window.$axios = service
  }
}

export {
  ryAxios
}
export default window.$axios
